/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.apache.nifi.processors.huawei.abstractprocessor;

import com.obs.services.ObsClient;
import com.obs.services.exception.ObsException;
import com.obs.services.model.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.nifi.annotation.lifecycle.OnScheduled;
import org.apache.nifi.components.ConfigVerificationResult;
import org.apache.nifi.flowfile.FlowFile;
import org.apache.nifi.logging.ComponentLog;
import org.apache.nifi.processor.ProcessContext;
import org.apache.nifi.processor.ProcessSession;
import org.apache.nifi.processor.VerifiableProcessor;
import org.apache.nifi.processors.huawei.obs.OBSRegions;
import org.apache.nifi.processors.huawei.obs.OBSUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import static org.apache.nifi.processors.huawei.common.PropertyDescriptors.*;
import static org.apache.nifi.processors.huawei.obs.Constants.*;

public abstract class AbstractOBSProcessor extends AbstractHuaweiProcessor implements VerifiableProcessor {
    protected volatile ObsClient client;
    @OnScheduled
    public void onScheduled(final ProcessContext context) {
        client = OBSUtils.createClient(context, getLogger());
    }

    @Override
    public List<ConfigVerificationResult> verify(final ProcessContext context, final ComponentLog verificationLogger, final Map<String, String> attributes) {
        final List<ConfigVerificationResult> results = new ArrayList<>();

        try {
            results.add(new ConfigVerificationResult.Builder()
                    .outcome(ConfigVerificationResult.Outcome.SUCCESSFUL)
                    .verificationStepName("Create Client and Configure Region")
                    .explanation("Successfully created OBS Client and configured Region")
                    .build());
        } catch (final Exception e) {
            verificationLogger.error("Failed to create OBS Client", e);
            results.add(new ConfigVerificationResult.Builder()
                    .outcome(ConfigVerificationResult.Outcome.FAILED)
                    .verificationStepName("Create Client and Configure Region")
                    .explanation("Failed to crete OBS Client or configure Region: " + e.getMessage())
                    .build());
        }
        return results;
    }

    protected GranteeInterface createGrantee(final String value) {
        if (StringUtils.isBlank(value)) {
            return null;
        }
        return new CanonicalGrantee(value);
    }

    protected final List<GranteeInterface> createGrantees(final String value) {
        if (StringUtils.isBlank(value)) {
            return Collections.emptyList();
        }

        final List<GranteeInterface> grantees = new ArrayList<>();
        final String[] values = value.split(",");
        for (final String val : values) {
            final String identifier = val.trim();
            final GranteeInterface grantee = createGrantee(identifier);
            if (grantee != null) {
                grantees.add(grantee);
            }
        }
        return grantees;
    }

    /**
     * Create AccessControlList if appropriate properties are configured.
     *
     * @param context  ProcessContext
     * @param flowFile FlowFile
     * @return AccessControlList or null if no ACL properties were specified
     */
    protected final AccessControlList createACL(final ProcessContext context, final FlowFile flowFile) {
        AccessControlList acl = null;

        final String ownerId = context.getProperty(OWNER).evaluateAttributeExpressions(flowFile).getValue();
        if (StringUtils.isNotBlank(ownerId)) {
            final Owner owner = new Owner();
            owner.setId(ownerId);
            if (acl == null) {
                acl = new AccessControlList();
            }
            acl.setOwner(owner);
            acl.grantPermission(new CanonicalGrantee(ownerId), Permission.PERMISSION_FULL_CONTROL);
        }

        for (final GranteeInterface grantee : createGrantees(context.getProperty(FULL_CONTROL_USER_LIST).evaluateAttributeExpressions(flowFile).getValue())) {
            if (acl == null) {
                acl = new AccessControlList();
            }
            acl.grantPermission(grantee, Permission.PERMISSION_FULL_CONTROL);
        }

        for (final GranteeInterface grantee : createGrantees(context.getProperty(READ_USER_LIST).evaluateAttributeExpressions(flowFile).getValue())) {
            if (acl == null) {
                acl = new AccessControlList();
            }
            acl.grantPermission(grantee, Permission.PERMISSION_READ);
        }

        for (final GranteeInterface grantee : createGrantees(context.getProperty(READ_ACL_LIST).evaluateAttributeExpressions(flowFile).getValue())) {
            if (acl == null) {
                acl = new AccessControlList();
            }
            acl.grantPermission(grantee, Permission.PERMISSION_READ_ACP);
        }

        for (final GranteeInterface grantee : createGrantees(context.getProperty(WRITE_ACL_LIST).evaluateAttributeExpressions(flowFile).getValue())) {
            if (acl == null) {
                acl = new AccessControlList();
            }
            acl.grantPermission(grantee, Permission.PERMISSION_WRITE_ACP);
        }

        return acl;
    }

    protected FlowFile extractExceptionDetails(final Exception e, final ProcessSession session, FlowFile flowFile) {
        flowFile = session.putAttribute(flowFile, OBS_EXCEPTION, e.getClass().getName());
        if (e instanceof ObsException) {
            flowFile = putAttribute(session, flowFile, OBS_ERROR_CODE, ((ObsException) e).getErrorCode());
            flowFile = putAttribute(session, flowFile, OBS_ERROR_Message, ((ObsException) e).getErrorMessage());
            flowFile = putAttribute(session, flowFile, OBS_ADDITIONAL_DETAILS, ((ObsException) e).getXmlMessage());
            return flowFile;

        }
         return putAttribute(session, flowFile, OBS_ERROR_Message, e.getMessage());
    }

    private FlowFile putAttribute(final ProcessSession session, final FlowFile flowFile, final String key, final Object value) {
        return (value == null) ? flowFile : session.putAttribute(flowFile, key, value.toString());
    }

    /**
     * Create CannedAccessControlList if CANNED_ACL property specified.
     *
     * @param context  ProcessContext
     * @param flowFile FlowFile
     * @return CannedAccessControlList or null if not specified
     */
    protected final AccessControlList createCannedACL(final ProcessContext context, final FlowFile flowFile) {
        final String cannedAclString = context.getProperty(CANNED_ACL).evaluateAttributeExpressions(flowFile).getValue();
        if (StringUtils.isNoneBlank(cannedAclString)) {
            switch (cannedAclString) {
                case "Private":
                    return AccessControlList.REST_CANNED_PRIVATE;
                case "PublicRead":
                    return AccessControlList.REST_CANNED_PUBLIC_READ;
                case "PublicReadWrite":
                    return AccessControlList.REST_CANNED_PUBLIC_READ_WRITE;
                case "PublicReadWriteDelivered":
                    return AccessControlList.REST_CANNED_PUBLIC_READ_WRITE_DELIVERED;
                default:
            }
        }
        return null;
    }




    public ObsClient getClient() {
        return client;
    }
}
